<template>
  <view>
    <view class="spec-set page100 flex-col" :style="{ '--theme': themeColor }">
      <nav-bar title="规格设置" />
      <view class="top flex text-29 marginBottom-20" ref="top">
        <view
          :class="['flex1', 'center', 'tab', index === active ? 'active' : '']"
          v-for="(item, index) in tabList"
          :key="index"
          @click="changeTab(index)"
          >{{ item }}</view
        >
      </view>
      <view class="list flex1 flex-col" v-if="active == 0">
        <scroll-view scroll-y class="flex1" v-if="specList.length > 0">
          <view v-for="(item, index) in specList" :key="index">
            <spec-com
              :spec="item"
              @upData="getData"
              @addAttr="addAttr($event, index)"
              @deleteAttr="deleteAttr($event, index)"
              @deleteSpec="deleteSpec($event, index)"
            />
          </view>
        </scroll-view>
        <xh-empty title="暂无相关规格数据" class="flex1" v-else />
      </view>
      <view class="list flex1 flex-col" v-else>
        <view v-if="showTabSku" class="flex1 flex-col">
          <view class="shop" @click="showChoose = true">
            <u--input
              disabledColor="#fff"
              :disabled="true"
              placeholder="请输入内容"
              v-model="selectPar.storeName"
              suffixIcon="arrow-down"
            />
          </view>
          <view class="flex1" v-if="skuList.length > 0">
            <view
              v-for="(item, index) in storeLists[currentShopIndex].skus"
              :key="`${index}`"
            >
              <u--form
                :model="storeLists[currentShopIndex].skus[index]"
                :rules="rules"
                :ref="`form_${index}_ref`"
                labelWidth="70px"
              >
                <view class="flex sku">
                  <view class="flex1">
                    <view class="flex flexAIC sku-top">
                      <view v-if="isBatch" class="radio">
                        <u-checkbox
                          @change="childCheck($event, index)"
                          :checked="isChecked(index)"
                        />
                      </view>
                      <view class="flex1 flex-btw">
                        <view class="title">{{ item.specAttrNameList }}</view>
                        <view class="flex">
                          <view class="marginRight-13">上下架</view>
                          <u-switch
                            v-model="
                              storeLists[currentShopIndex].skus[index].status
                            "
                            :activeValue="1"
                            :inactiveValue="0"
                            inactiveColor="#dcdfe6"
                            size="19"
                          />
                        </view>
                      </view>
                    </view>
                    <u-form-item prop="price" label="价格/元">
                      <u--input
                        type="number"
                        v-model="storeLists[currentShopIndex].skus[index].price"
                        maxlength="10"
                        :showWordLimit="true"
                        placeholder="请输入售卖价格"
                      />
                    </u-form-item>
                    <u-form-item label="库存" prop="inventory">
                      <u--input
                        type="number"
                        v-model="
                          storeLists[currentShopIndex].skus[index].inventory
                        "
                        maxlength="10"
                        :showWordLimit="true"
                        placeholder="请输入售卖库存"
                      />
                    </u-form-item>
                  </view>
                </view>
              </u--form>
            </view>
          </view>
        </view>
        <xh-empty title="暂无数据" class="flex1" v-if="!showTabSku" />
      </view>
      <view class v-if="!isBatch">
        <view class="bottom" v-if="active === 0">
          <u-button
            v-if="pubUserInfo.mainShopStatus"
            type="primary"
            :disabled="specList.length > 2"
            @click="showAdd = true"
            >添加规格</u-button
          >
        </view>
        <view class="bottom flex" v-if="active === 1 && showTabSku">
          <u-button class="batch-btn" @click="isBatch = true"
            >批量操作</u-button
          >
          <u-button type="primary" @click="save()">保存</u-button>
        </view>
      </view>
      <view class="batch flex flexAIC" v-else>
        <view class="radio flex">
          <u-checkbox v-model="isAll" :checked="isAll" @change="changeIsall" />
          <view class="radio-text marginLeft-12">全选</view>
        </view>
        <view class="flex flex1 flex-end batch-btns flexAIC">
          <view @click="isBatch = false">退出批量</view>
          <view
            @click="showBatch()"
            :style="{
              opacity: checkedList.length > 0 ? 1 : 0.3,
            }"
            >批量修改
          </view>
        </view>
      </view>
    </view>
    <add-spec-val
      :visible.sync="showAdd"
      :specList="specList"
      @addSpec="addSpec"
    />
    <choose-shop
      :visible.sync="showChoose"
      @chooseClass="chooseShop"
      :activeStoreId="selectPar.shopId"
      :isShowAll="false"
      activeFiled="shopId"
    />
    <batch-modal :visible.sync="showBatchModal" @submitBatch="submitBatch" />
  </view>
</template>
<script>
import specCom from "@/components/pageComponents/sp-product/spec-com";
import addSpecVal from "@/components/pageComponents/sp-product/add-spec";
import { chooseShop } from "@/components/pageComponents/sp-product/choose-shop";

import skuCom from "@/components/pageComponents/sp-product/sku-com";
import batchModal from "@/components/pageComponents/sp-product/batch-modal";
import { getStoreList } from "@/service/api/sp-product/index";
import { mapState, mapActions } from "vuex";

export default {
  components: {
    addSpecVal,
    specCom,
    chooseShop,
    skuCom,
    batchModal,
  },
  data() {
    return {
      rules: {
        price: [
          {
            type: "number",
            required: true,
            message: "此为必填字段",
            trigger: ["blur", "change"],
          },
        ],
        inventory: [
          {
            type: "number",
            required: true,
            message: "此为必填字段",
            trigger: ["blur", "change"],
          },
        ],
      },
      active: 0, // tab值
      tabList: ["规格", "价格/库存"],
      isBatch: false,
      isAll: false,
      skuList: [],
      specList: [],
      checkedList: [],
      showBatchModal: false,
      storeLists: [],
      showAdd: false,
      showChoose: false,
      selectPar: {
        name: "",
        shopId: "",
      },
      type: "add",
      currentShopSkus: [],
      showTabSku: true,
    };
  },
  async mounted() {
    this.skuList = JSON.parse(JSON.stringify(this.vxSkus));
    this.specList = JSON.parse(JSON.stringify(this.vxspecList));
    this.storeLists = JSON.parse(JSON.stringify(this.vxstoreList));
    await this.getStoreList();
    await this.initStrolist();
  },
  computed: {
    isChecked() {
      return function (index) {
        return this.checkedList.indexOf(index) > -1;
      };
    },
    currentShopIndex() {
      return this.storeLists.findIndex((item) => {
        return item.shopId == this.selectPar.shopId;
      });
    },
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
    ...mapState("sp-common/auth", ["pubUserInfo"]),
    ...mapState("sp-product/index", {
      vxSkus: "skuList",
      vxspecList: "specList",
      vxstoreList: "storeList",
    }),
  },
  watch: {
    "selectPar.shopId"(val) {
      this.initCheckList();
    },
    specList: {
      handler(newVal) {
        this.checkSpec();
      },
      deep: true,
    },
  },

  methods: {
    ...mapActions("sp-product/index", [
      "setSkuList",
      "setSpecList",
      "setStoreList",
    ]),
    // tab切换
    changeTab(index) {
      if (index == this.active) return;
      this.isBatch = false;
      this.active = index;
    },
    // 勾选全部操作
    changeIsall(e) {
      this.isAll = e;
      let { currentShopSkus } = this;
      this.checkedList = e ? JSON.parse(JSON.stringify(currentShopSkus)) : [];
    },
    // 获取门店列表
    getStoreList() {
      return new Promise((resolve) => {
        getStoreList({ disabled: false }).then((res) => {
          this?.vxstoreList?.length <= 0 ? (this.storeLists = res) : "";
          let { shopId, storeName } = res[0];
          this.selectPar = {
            shopId,
            storeName,
          };
          resolve();
        });
      });
    },
    // 批量修改
    submitBatch(batchForm) {
      let { price, inventory, isOpen } = batchForm;
      let { checkedList, currentShopIndex } = this;
      console.log(checkedList);
      if (checkedList.length > 0) {
        checkedList.forEach((item) => {
          this.storeLists[currentShopIndex].skus[item].price = price;
          this.storeLists[currentShopIndex].skus[item].status = isOpen;
          this.storeLists[currentShopIndex].skus[item].inventory = inventory;
        });
        this.checkedList = [];
        this.isAll = false;
      }
    },
    // 添加规格
    addSpec(row) {
      row.attrList = [];
      this.specList.push(row);
      this.skuBuilder();
    },
    // 添加规格值
    addAttr(e, index) {
      this.specList[index].attrList.push(e);
      this.initStrolist();
    },
    // 保存
    save() {
      let { $refs } = this;
      let statusNum = 0;
      let forms = Object.keys($refs).filter((ele) => {
        return ele.indexOf("form") > -1;
      });
      const res = forms.map(async (item, index) => {
        let sta = await this.$refs[item][0].validate();
        if (sta) statusNum++;
        return item;
      });
      Promise.allSettled(res).then(() => {
        if (forms.length === statusNum) {
          this.saveSpecs().then(() => {
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2]; //上一页页面实例
            prevPage.$vm.saveSpec();
            uni.navigateBack({
              delta: 1,
            });
          });
        }
      });
    },
    // 生成sku
    skuBuilder() {
      return new Promise((resolve) => {
        const specList = JSON.parse(JSON.stringify(this.specList));
        const attrIdsArr = [];
        const attrNameObj = {};
        // if (!this.showTabSku) return;
        specList.forEach((spec, specIndex) => {
          const attrIds = [];
          spec.attrList.forEach((attr, attrIndex) => {
            attrIds.push(attr.id);
            attrNameObj[attr.id] = attr.title;
          });
          attrIdsArr.push(attrIds);
        });
        // 获取sku所有组合
        const skuIdsArr = skuList(...attrIdsArr);
        // 生成table列表 匹配原有表格数据存在则不插新数据
        const tableListNew = [];
        skuIdsArr.forEach((idsArr) => {
          const specAttrNameList = [];
          const skuObj = {
            imgUrl: "",
            originPrice: "",
            price: 0.01,
            skuNo: "",
            sn: "",
            inventory: 0,
            specAttrNameList: [],
            specAttrIdsList: idsArr,
            status: 0,
            specAttr1: 0,
            specAttr2: 0,
            specAttr3: 0,
            specAttr4: 0,
            specAttr5: 0,
            specAttr6: 0,
          };
          idsArr.forEach((id, idIndex) => {
            specAttrNameList.push(attrNameObj[id]);
            skuObj["specAttr" + (idIndex + 1)] = id;
          });
          skuObj.specAttrNameList = specAttrNameList;
          tableListNew.push(skuObj);
        });
        // 判断是否已经存在 存在则使用旧数据
        tableListNew.forEach((newItem, newItemIndex) => {
          this.skuList.forEach((oldItem) => {
            const newItemString = JSON.stringify(
              newItem.specAttrNameList.sort()
            );
            const oldItemString = JSON.stringify(
              oldItem.specAttrNameList.sort()
            );
            if (newItemString === oldItemString) {
              tableListNew.splice(newItemIndex, 1, oldItem);
            }
          });
        });

        // 赋值
        this.skuList = tableListNew;
        // 生成所有sku组合
        function skuList() {
          return Array.prototype.reduce.call(
            arguments,
            function (a, b) {
              if (b.length === 0) {
                return a;
              }
              let ret = [];
              a.forEach(function (a) {
                b.forEach(function (b) {
                  ret.push(a.concat([b]));
                });
              });
              return ret;
            },
            [[]]
          );
        }
        resolve();
      });
    },
    // 初始化门店所有sku
    async initStrolist() {
      await this.skuBuilder();
      let { skuList, storeLists } = this;
      storeLists.forEach((ele) => {
        let cloneSkuList = JSON.parse(JSON.stringify(skuList));
        if (ele?.skus?.length > 0) {
          let childSkus = ele?.skus.map((ele) => {
            return ele?.specAttrNameList.sort().toString();
          });
          cloneSkuList.forEach((element, index) => {
            if (
              childSkus.indexOf(element?.specAttrNameList.sort().toString()) >
              -1
            ) {
              cloneSkuList[index] =
                ele.skus[
                  childSkus.indexOf(element?.specAttrNameList.sort().toString())
                ];
            }
          });
          ele.skus = cloneSkuList;
        } else {
          ele.skus = cloneSkuList;
        }
      });
      this.storeLists = JSON.parse(JSON.stringify(storeLists));
    },
    // 门店sku勾选操作
    childCheck(e, index) {
      let { currentShopSkus } = this;
      e
        ? this.checkedList.push(index)
        : this.checkedList.splice(this.checkedList.indexOf(index), 1);
      this.isAll =
        currentShopSkus.toString() == this.checkedList.toString()
          ? true
          : false;
    },
    // 筛选门店
    chooseShop(data) {
      this.selectPar = data.storeData;
    },

    deleteAttr(e, index) {
      this.specList[index].attrList = e;
      this.initStrolist();
    },
    deleteSpec(e, index) {
      uni.showModal({
        content: "是否删除规格？删除后对应规格值也将一起删除，请谨慎操作",
        success: (res) => {
          if (res.confirm) {
            this.specList.splice(index, 1);
            this.initStrolist();
          }
        },
      });
    },
    initCheckList() {
      this.$nextTick(() => {
        let { storeLists, currentShopIndex, currentShopSkus = [] } = this;
        if (storeLists[currentShopIndex]?.skus?.length > 0) {
          storeLists[currentShopIndex].skus.forEach((ele, index) => {
            currentShopSkus.push(index);
          });
        }
      });
    },
    saveSpecs() {
      return new Promise((resolve, reject) => {
        let { storeLists, skuList, specList } = this;
        this.setSkuList(skuList);
        this.setSpecList(specList);
        this.setStoreList(storeLists);
        resolve();
      });
    },
    checkSpec() {
      let { specList } = this;
      if (specList?.length <= 0) {
        this.showTabSku = false;
      } else {
        let falg = false;
        specList.forEach((ele) => {
          if (ele?.attrList?.length > 0) {
            falg = true;
          }
        });
        this.showTabSku = falg;
      }
    },
    showBatch() {
      if (this.checkedList.length <= 0) return;
      this.showBatchModal = true;
    },
  },
  // 临时保存数据
  beforeDestroy() {
    this.saveSpecs();
  },
};
</script>
<style lang="scss" scoped>
@import "../../css/spec-set.scss";
</style>
